import { toSuccess, useEntityManager } from "@sker/core"
import { KsAccount, KsLiveRoom, KsRedPacket } from "@sker/entities"
import { useData } from "@sker/runtime"
import dayjs from "dayjs"
import { z } from "zod"

export default async () => {
    const input = z.object({
        type: z.optional(z.string())
    });
    const end_time = dayjs().subtract(1, 'minute').toDate()
    const start_time = dayjs().subtract(10, 'minute').toDate()
    const body = input.parse(useData())
    body.type = body.type || '口令';
    const list = await useEntityManager(async m => {
        const list = await m.createQueryBuilder()
            .select('room.link', 'link')
            .addSelect('room.name', 'name')
            .addSelect('room.user_id', 'user_id')
            .addSelect('room.open_time', 'open_time')
            .addSelect(`account.ksid`, `ksid`)
            .from(KsLiveRoom, 'room')
            .leftJoin(KsRedPacket, 'red', 'red.room_id=room.id')
            .leftJoin(KsAccount, 'account', 'account.user_id=room.user_id')
            .where(`room.open_time<:end_time and room.open_time>:start_time`, { start_time: start_time, end_time: end_time })
            .andWhere('account.has_live=:has_live', { has_live: true })
            .andWhere('red.type=:type', { type: body.type })
            .orderBy('room.open_time', 'ASC')
            .limit(100)
            .execute()
        const uniqueUserIds = [...new Set(list.map(it => it.user_id))];

        return uniqueUserIds.map(user_id => {
            const item = list.find(it=>it.user_id === user_id)
            item.share = `kwai://live/play/~${item.user_id}`
            return item;
        })
    })
    return toSuccess(list)

}